
import os
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
import pickle
import json
import time
from urllib.parse import urlparse



def writetofile(path):
    with open(path, 'wb') as f:
        f.write("")



def InitCookieByFile(fpath):
    c=None
    cookies=''
    try:
        with open(fpath, 'r') as f:
            cookies = f.read()
            cookies = cookies.rstrip(' \r\n\t')
        c = json.loads(cookies)
    except json.decoder.JSONDecodeError as j:
        c = {i[:i.find('=')]:i[i.find('=')+1:] for i in cookies.split("; ")}
    except FileExistsError as e:
        print(e)
    return c


def readTaobaoCookies(cfile):
    # if hava cookies file ,use it
    # if not , getTaobaoCookies()
    if os.path.exists('taobaoCookies.pickle'):
        readPath = open('taobaoCookies.pickle','rb')
        tbCookies = pickle.load(readPath)
    else:
        tbCookies = InitCookieByFile(cfile)
    return tbCookies


def go(url, cookies, domain = ''):
    if domain == '':
        data = urlparse(url)
        domain = urlparse(url).netloc

    brower = webdriver.Chrome()
    wait = WebDriverWait(brower, 10)

    tbCookies = {i[:i.find('=')]:i[i.find('=')+1:] for i in cookies.split("; ")}

    brower.get(url)
    for cookie in tbCookies:
        brower.add_cookie({
            "domain":domain,
            "name":cookie,
            "value":tbCookies[cookie],
            "path":'/',
            "expires":None
        })
    brower.get(url)



if __name__ == "__main__":
    go('https://www.baidu.com', '')

